/**
 * Welcome to Cloudflare Workers! This is your first worker.
 *
 * - Run `npm run dev` in your terminal to start a development server
 * - Open a browser tab at http://localhost:8787/ to see your worker in action
 * - Run `npm run deploy` to publish your worker
 *
 * Bind resources to your worker in `wrangler.jsonc`. After adding bindings, a type definition for the
 * `Env` object can be regenerated with `npm run cf-typegen`.
 *
 * Learn more at https://developers.cloudflare.com/workers/
 */

import yaml from 'js-yaml'

const getClashConfig = async (clash_url: string) => {
	const response = await fetch(clash_url)
			
	if (!response.ok) {
		throw new Error(`HTTP error! status: ${response.status}`)
	}
	
	const content = await response.text()
	const data = yaml.load(content)

	const result: any = {
		"allow-lan": true,
		"dns": {
			"enable": true, 
			"enhanced-mode": "fake-ip", 
			"fake-ip-range": "198.18.0.1/16", 
			"default-nameserver": ["8.8.8.8", "114.114.114.114"],
			"nameserver": ["https://doh.pub/dns-query"]
		},
		"listeners": [],    
		"proxies": [],    
	}

	const startPort = 52000 // 起始端口
	const parsedData = data as any
	if (parsedData.proxies && Array.isArray(parsedData.proxies)) {
		parsedData.proxies.forEach((line: any, n: number) => {
			// 添加监听器
			result.listeners.push({
				name: `mixed${n}`,
				type: "mixed",
				port: startPort + n,
				proxy: line.name
			})
			
			// 添加代理
			result.proxies.push(line)
		})
	}
	return result
}

export default {
	async fetch(request, env, ctx): Promise<Response> {
		// 处理非 POST 请求，返回简约的使用说明
		if (request.method !== 'POST') {
			const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clash Socks5 转换器</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 40px 20px;
            line-height: 1.6;
            color: #333;
        }
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
        }
        .code {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            font-family: 'Monaco', 'Menlo', monospace;
            overflow-x: auto;
            margin: 15px 0;
        }
        .example {
            background: #e8f5e8;
            border-left: 3px solid #28a745;
            padding: 10px 15px;
            margin: 15px 0;
        }
        h2 {
            color: #495057;
            margin-top: 30px;
            margin-bottom: 15px;
        }
        .method {
            background: #007bff;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <h1>Clash Socks5 转换器</h1>
    
    <p>将 Clash 配置转换为多端口 Socks5 代理配置</p>

    <h2><span class="method">POST</span> 使用方法</h2>
    <div class="code"><pre>curl -X POST \\
    -H "Content-Type: application/json" \\
    -d '{"clash_url": "你的clash配置URL"}' \\
    ${new URL(request.url).origin}</pre>
    </div>

    <div class="example">
        <strong>参数：</strong> clash_url (必需) - Clash 配置文件 URL
    </div>
</body>
</html>`
			
			return new Response(html, {
				headers: {
					'Content-Type': 'text/html; charset=utf-8',
					'Access-Control-Allow-Origin': '*'
				}
			})
		}

		try {
			// 解析请求体中的 JSON 数据
			const requestData = await request.json() as { clash_url?: string; url?: string }
			const clash_url = requestData.clash_url || requestData.url

			if (!clash_url) {
				return new Response(JSON.stringify({ 
					error: '缺少 clash_url 参数',
					message: '请提供有效的 clash_url 参数',
					example: {
						clash_url: 'https://example.com/clash-config.yaml'
					}
				}, null, 2), {
					status: 400,
					headers: {
						'Content-Type': 'application/json',
						'Access-Control-Allow-Origin': '*'
					}
				})
			}

			const result = await getClashConfig(clash_url)
			return new Response(JSON.stringify(result, null, 2), {
				headers: {
					'Content-Type': 'application/json',
					'Access-Control-Allow-Origin': '*'
				}
			})
			
		} catch (error: any) {
			return new Response(JSON.stringify({ 
				error: error.message,
				message: '处理请求时发生错误',
				timestamp: new Date().toISOString()
			}, null, 2), {
				status: 500,
				headers: {
					'Content-Type': 'application/json',
					'Access-Control-Allow-Origin': '*'
				}
			})
		}
	},
} satisfies ExportedHandler<Env>;
